package com.example.petshopping.ui.settings;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.petshopping.R;
import com.example.petshopping.model.CommonResult;
import com.example.petshopping.network.RetrofitClient;
import com.example.petshopping.ui.address.AddressActivity;
import com.example.petshopping.ui.login.LoginActivity;
import com.example.petshopping.utils.TokenManager;

import java.io.File;
import java.text.DecimalFormat;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class SettingsActivity extends AppCompatActivity {
    
    private static final String TAG = "SettingsActivity";
    
    private TextView tvNickname;
    private TextView tvCacheSize;
    private Switch switchPush;
    private View btnBack;
    private View layoutAvatar;
    private View layoutNickname;
    private View layoutAddress;
    private View layoutClearCache;
    private View layoutAbout;
    private View layoutLogout;
    private View layoutDeleteAccount;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settings);
        
        initViews();
        setupListeners();
        loadUserData();
    }

    private void initViews() {
        btnBack = findViewById(R.id.btn_back);
        tvNickname = findViewById(R.id.tv_nickname);
        tvCacheSize = findViewById(R.id.tv_cache_size);
        switchPush = findViewById(R.id.switch_push);
        
        layoutAvatar = findViewById(R.id.layout_avatar);
        layoutNickname = findViewById(R.id.layout_nickname);
        layoutAddress = findViewById(R.id.layout_address);
        layoutClearCache = findViewById(R.id.layout_clear_cache);
        layoutAbout = findViewById(R.id.layout_about);
        layoutLogout = findViewById(R.id.layout_logout);
        layoutDeleteAccount = findViewById(R.id.layout_delete_account);
    }

    private void setupListeners() {
        // 返回按钮
        btnBack.setOnClickListener(v -> finish());
        
        // 头像点击
        layoutAvatar.setOnClickListener(v -> {
            Toast.makeText(this, "头像功能即将上线", Toast.LENGTH_SHORT).show();
        });
        
        // 昵称点击
        layoutNickname.setOnClickListener(v -> {
            showEditNicknameDialog();
        });
        
        // 收货地址点击
        layoutAddress.setOnClickListener(v -> {
            Intent intent = new Intent(this, AddressActivity.class);
            startActivity(intent);
        });
        
        // 清除缓存点击
        layoutClearCache.setOnClickListener(v -> {
            showClearCacheDialog();
        });
        
        // 推送开关
        switchPush.setOnCheckedChangeListener((buttonView, isChecked) -> {
            updatePushSettings(isChecked);
        });
        
        // 关于我们点击
        layoutAbout.setOnClickListener(v -> {
            Toast.makeText(this, "关于我们功能即将上线", Toast.LENGTH_SHORT).show();
        });
        
        // 退出登录点击
        layoutLogout.setOnClickListener(v -> {
            showLogoutConfirmDialog();
        });
        
        // 注销账号点击
        layoutDeleteAccount.setOnClickListener(v -> {
            showDeleteAccountConfirmDialog();
        });
    }

    private void loadUserData() {
        // 加载用户数据
        tvNickname.setText("Li");
        
        // 计算缓存大小
        String cacheSize = calculateCacheSize();
        tvCacheSize.setText(cacheSize);
        
        // 设置推送开关状态
        switchPush.setChecked(true);
    }

    private String calculateCacheSize() {
        try {
            File cacheDir = getCacheDir();
            long size = getDirSize(cacheDir);
            return formatFileSize(size);
        } catch (Exception e) {
            Log.e(TAG, "计算缓存大小失败", e);
            return "0B";
        }
    }

    private long getDirSize(File dir) {
        if (dir == null || !dir.exists()) {
            return 0;
        }
        
        long size = 0;
        File[] files = dir.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    size += getDirSize(file);
                } else {
                    size += file.length();
                }
            }
        }
        return size;
    }

    private String formatFileSize(long size) {
        if (size <= 0) return "0B";
        
        final String[] units = new String[]{"B", "KB", "MB", "GB", "TB"};
        int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
        
        DecimalFormat df = new DecimalFormat("#.##");
        return df.format(size / Math.pow(1024, digitGroups)) + units[digitGroups];
    }

    private void showEditNicknameDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("修改昵称")
                .setMessage("昵称修改功能即将上线")
                .setPositiveButton("确定", null)
                .show();
    }

    private void showClearCacheDialog() {
        new AlertDialog.Builder(this)
                .setTitle("清除缓存")
                .setMessage("确定要清除所有缓存吗？")
                .setPositiveButton("确定", (dialog, which) -> {
                    clearCache();
                })
                .setNegativeButton("取消", null)
                .show();
    }

    private void clearCache() {
        try {
            File cacheDir = getCacheDir();
            deleteDir(cacheDir);
            
            // 重新计算缓存大小
            String newSize = calculateCacheSize();
            tvCacheSize.setText(newSize);
            
            Toast.makeText(this, "缓存清除成功", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Log.e(TAG, "清除缓存失败", e);
            Toast.makeText(this, "清除缓存失败", Toast.LENGTH_SHORT).show();
        }
    }

    private void deleteDir(File dir) {
        if (dir == null || !dir.exists()) {
            return;
        }
        
        File[] files = dir.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    deleteDir(file);
                } else {
                    file.delete();
                }
            }
        }
    }

    private void updatePushSettings(boolean enabled) {
        // 更新推送设置
        if (enabled) {
            Toast.makeText(this, "已开启消息推送", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "已关闭消息推送", Toast.LENGTH_SHORT).show();
        }
    }

    private void showLogoutConfirmDialog() {
        new AlertDialog.Builder(this)
                .setTitle("退出登录")
                .setMessage("确定要退出登录吗？")
                .setPositiveButton("确定", (dialog, which) -> {
                    logout();
                })
                .setNegativeButton("取消", null)
                .show();
    }

        private void logout() {
        // 获取当前保存的token
        String token = TokenManager.getToken(this);
        
        if (token == null) {
            // 如果没有token，直接跳转到登录页面
            navigateToLogin();
            return;
        }
        
        // 调用退出登录API（拦截器会自动添加Authorization头部）
        RetrofitClient.getInstance().getApiService().logout()
                .enqueue(new Callback<CommonResult<Boolean>>() {
                    @Override
                    public void onResponse(Call<CommonResult<Boolean>> call, Response<CommonResult<Boolean>> response) {
                        // 检查响应是否成功
                        boolean isSuccess = false;
                        if (response.isSuccessful() && response.body() != null && response.body().isSuccess()) {
                            isSuccess = true;
                        }
                        handleLogoutComplete(isSuccess);
                    }
                    
                    @Override
                    public void onFailure(Call<CommonResult<Boolean>> call, Throwable t) {
                        Log.e(TAG, "退出登录请求失败", t);
                        // 即使网络请求失败，也要清理本地token
                        handleLogoutComplete(false);
                    }
                });
    }
    
    private void handleLogoutComplete(boolean isNetworkSuccess) {
        // 清理本地保存的token和用户信息
        TokenManager.logout(this);
        
        // 显示提示信息
        if (isNetworkSuccess) {
            Toast.makeText(this, "退出登录成功", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "网络异常，已清理本地登录信息", Toast.LENGTH_SHORT).show();
        }
        
        // 跳转到登录页面
        navigateToLogin();
    }
    
    private void navigateToLogin() {
        Intent intent = new Intent(this, LoginActivity.class);
        // 确保登录页面是唯一的
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
        // 禁用页面切换动画
        overridePendingTransition(0,0);
        finish();
    }

    private void showDeleteAccountConfirmDialog() {
        new AlertDialog.Builder(this)
                .setTitle("注销账号")
                .setMessage("注销账号后，所有数据将被永久删除且无法恢复，确定要继续吗？")
                .setPositiveButton("确定", (dialog, which) -> {
                    // 注销账号逻辑
                    Toast.makeText(this, "账号注销功能即将上线", Toast.LENGTH_SHORT).show();
                })
                .setNegativeButton("取消", null)
                .show();
    }
} 